#include <glib.h>
#include "common.h"

void display_list(GList *list)
{
	GList *it = NULL;
	int  i = 0;
	/* 遍历链表 */
	for (it = list; it; it = it->next) {
		g_printf("[%d] [%p] %s", ++i, it->data, it->data);

	}

	g_printf("\n");

}

int main(int argc, char *argv[])
{
	GList *list = NULL;

	g_printf("length:%d\n", g_list_length(list));

	/* 向链表尾部追加节点 */
	list = g_list_append(list, "one ");
	g_printf("length:%d\n", g_list_length(list));
	list = g_list_append(list, 0);
	g_printf("length:%d\n", g_list_length(list));
	list = g_list_append(list, 0);
	g_printf("length:%d\n", g_list_length(list));
	list = g_list_append(list, 0);
	g_printf("length:%d\n", g_list_length(list));
	list = g_list_append(list, "two ");
	list = g_list_append(list, "three ");
	list = g_list_append(list, "four ");
	list = g_list_append(list, "five ");
	display_list(list);
	g_printf("length:%d\n", g_list_length(list));

	/* 在链表头部插入*/
	list = g_list_prepend(list, "zero ");
	display_list(list);
	g_printf("length:%d\n", g_list_length(list));

	GList *it = NULL;

	/* 查找链表中的节点 */
	it = g_list_find(list, "two ");
	g_printf("Find data two : %s\n", it->data);

	int index = 0;

	/* 确定链表指针指向链表中的第几个节点 */
	index = g_list_position(list, it);
	g_printf("index of two is: %d\n", index);

	it = g_list_nth(list, 1);
	g_printf("index of one is: %s\n", it->data);

	/* 从链表里删除一个节点 */
	g_printf("After remove data three , the list:\n");
	list = g_list_remove(list, "three ");
	display_list(list);
	g_printf("length:%d\n", g_list_length(list));

	/* 向链表里插入一个节点 */
	g_printf("After insert string INSERT at index 3, the list:\n");
	list = g_list_insert(list, "INSERT ", 3);
	display_list(list);
	g_printf("length:%d\n", g_list_length(list));

	/* 采用内循环遍历链表节点 */
	g_printf("start :");
	g_list_foreach(list, (GFunc)g_printf, NULL);
	g_printf("\n");

	GList *last = NULL;

	/* 取链表的最后一个节点 */
	last = g_list_last(list);

	/* 从最后一个节点开始遍历链表 */
	for (it = last; it; it = it->prev) {
		g_printf("%s", it->data);

	}
	g_printf("\n");

	/* 销毁链表 */
	g_printf("length:%d\n", g_list_length(list));
	g_list_free(list);
	//list = NULL;
	display_list(list);
	g_printf("length:%d\n", g_list_length(list));
	list = g_list_append(list, "one ");
	g_printf("length:%d\n", g_list_length(list));
	display_list(list);
	g_list_free(list);
	g_free(list);
	g_free(list->data);
	g_printf("length:%d\n", g_list_length(list));

	return 0;

} 
